<style scoped>
.search {
  width: 200px;
  float: right;
}
.commons {
  line-height: 1;
}
.userinput > form {
  width: 100%;
  padding: 0;
}
.ivu-form-item {
  margin-bottom: 5px;
}
.info_button {
  margin-left: 5px;
}
</style>
<template>
  <div class="commons">
    <div class="userinput">
      <Form ref="infoForm" :label-width="80" label-colon>
        <Row type="flex" justify="start" class="code-row-bg">
          <Col span="6">
            <FormItem :label-width="60" label="系统">
              <Select v-model="batch" placeholder="默认为全系统数据">
                <Option value>全部</Option>
                <Option
                  v-for="item in this.selectArr"
                  :key="item.batch"
                  :value="item.batch"
                >{{ item.batchName }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem :label-width="60" label="状态">
              <Select v-model="queryParams.execflag" placeholder="默认为全部状态">
                <Option value>全部</Option>
                <Option :value="0">等待</Option>
                <Option :value="1">进行中</Option>
                <Option :value="2">失败</Option>
                <Option :value="3">成功</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="原表名">
              <Input v-model="queryParams.srctable" placeholder="请输入源库表名称" clearable />
            </FormItem>
          </Col>
          <Col span="6">
            <Button type="primary" @click="swichBatch" class="info_button">查询</Button>
            <Button type="success" class="info_button" @click="addFun">新建任务</Button>
          </Col>
        </Row>
      </Form>
    </div>
    <Table
      stripe
      border
      :height="this.windowHeight - 200"
      :columns="columns"
      :data="data"
      ref="tables"
      size="small"
      :tooltip-theme="menuTheme"
      :loading="loading"
    ></Table>
    <Page
      :total="totals"
      show-sizer
      :style="{padding:'15px'}"
      :page-size="sizes"
      @on-change="swichPage"
      @on-page-size-change="swichSize"
    />
    
    <Modal v-model="modal" title="添加任务" width="1312" footer-hide :mask-closable="false">
      <Add v-if="modal" v-on:fun="change" :menuTheme="this.menuTheme" />
    </Modal>


    <Modal v-model="updateModal" title="修改任务" width="1312" footer-hide :mask-closable="false">
      <Update
        v-if="updateModal"
        v-on:fun="updateChange"
        :selected="this.selected"
        :menuTheme="this.menuTheme"
      />
    </Modal>


    <Modal
      v-model="socketModal"
      title="执行任务"
      width="1312"
      :mask-closable="false"
      scrollable
      @on-visible-change="socketClose"
    >
      <websocket
        v-if="socketModal"
        :menuTheme="this.menuTheme"
        :executeTaskData="this.executeTaskData"
		     etlTaskType="main"
         interfaceType="increment"
      />
      <div
        slot="footer"
        :style="{color:'#808695',fontSize:'12px',textAlign:'center'}"
      >温馨提示：关闭窗口后，任务将在后台继续执行。</div>
    </Modal>
    <Modal v-model="historyModal" title="执行历史" width="750" footer-hide :mask-closable="false">
      <LogList v-if="historyModal" :logKid="this.logKid" logType="increment" />
    </Modal>
  </div>
</template>
<script>
import Add from "./add";
import Update from "./update";
import websocket from "../websocket/index";
import LogList from "../logs/list";
export default {
  name: "List",
  components: {
    Add,
    Update,
    websocket,
    LogList
  },
  props: {
    menuTheme: String,
    windowHeight: Number
  },
  data() {
    return {
      queryParams: {
        srctable: "",
        execflag: ""
      },
      loading: true,
      columns: [
        {
          title: "序号",
          type: "index",
          width: 70,
          align: "center"
        },
        {
          title: "批次号",
          key: "batch",
          width: 80,
          align: "center"
        },
        {
          title: "批次名称",
          key: "batchName",
          width: 120,
          align: "center"
        },
        {
          title: "源库",
          key: "sourceDbSysname",
          minWidth: 100,
          tooltip: true
        },
        {
          title: "源表",
          key: "sourceTableName",
          align: "center",
          width: 200,
          tooltip: true
        },
        {
          title: "目标库",
          key: "targetDbSysname",
          align: "center",
          width: 100,
          tooltip: true
        },
        {
          title: "目标表",
          key: "targetTableName",
          align: "center",
          width: 200,
          tooltip: true
        },
        {
          title: "表描述",
          key: "tableComment",
          align: "center",
          width: 170,
          tooltip: true
        },
        {
          title: "抽取单位",
          key: "commitSize",
          width: 90,
          align: "center"
        },
        {
          title: "抽取状态",
          key: "execFlag",
          align: "center",
          width: 110,
          render: (h, params) => {
            if (params.row.execFlag === 0) {
              return h(
                "Tag",
                {
                  props: {
                    color: "primary",
                    type: "border"
                  }
                },
                "Waiting"
              );
            } else if (params.row.execFlag === 1) {
              return h(
                "Tag",
                {
                  props: {
                    color: "warning",
                    type: "border"
                  }
                },
                "Running"
              );
            } else if (params.row.execFlag === 2) {
              return h(
                "Tag",
                {
                  props: {
                    color: "error",
                    type: "border"
                  }
                },
                "Error"
              );
            } else {
              return h(
                "Tag",
                {
                  props: {
                    color: "success",
                    type: "border"
                  }
                },
                "Success"
              );
            }
          }
        },
        {
          title: "定时状态",
          key: "flag",
          align: "center",
          width: 110,
          render: (h, params) => {
            if (params.row.flag === 1) {
              return h(
                "Tag",
                {
                  props: {
                    color: "success",
                    type: "border"
                  }
                },
                "已开启"
              );
            } else {
              return h(
                "Tag",
                {
                  props: {
                    color: "warning",
                    type: "border"
                  }
                },
                "已关闭"
              );
            }
          }
        },
        {
          title: "最后成功抽取",
          align: "center",
          key: "dataLastExtractTime",
          width: 150,
          render: (h, params) => {
            if (params.row.dataLastExtractTime) {
              return h("span", params.row.dataLastExtractTime);
            } else {
              return h(
                "Tag",
                {
                  props: {
                    color: "error",
                    type: "border"
                  }
                },
                "从未抽取"
              );
            }
          }
        },
        {
          title: "任务添加时间",
          align: "center",
          key: "createTime",
          width: 150
        },
        {
          title: "操作",
          width: 235,
          align: "center",
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "info",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.updateFun(params);
                    }
                  }
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "success",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.execute(params);
                    }
                  }
                },
                "执行"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.history(params);
                    }
                  }
                },
                "历史"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.deleteTask(params);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data: [],
      modal: false,
      updateModal: false,
      socketModal: false,
      historyModal: false,
      batch: "",
      sizes: 20,
      currentPage: 1,
      totals: 0,
      selected: "",
      logKid: 0,
      logType:"",
      selectArr: [],
      deleteContent: "",
      executeTaskData: 0
    };
  },
  methods: {
    //切换页码
    swichPage(page) {
      this.currentPage = page;
      this.getEtlIncrementTaskList(this.currentPage);
    },
    //切换每页容量
    swichSize(size) {
      this.sizes = size;
      this.getEtlIncrementTaskList(this.currentPage);
    },
    //获取任务列表
    async getEtlIncrementTaskList(pages) {
      const data = {
        pages,
        sizes: this.sizes,
        batch: this.batch
      };
      Object.assign(data, this.queryParams);
      this.loading = true;
      const result = await this.$api.getEtlIncrementTaskList(data);
      this.loading = false;
      if (result.code === 1) {
        this.data = result.data.list;
        this.totals = result.data.total;
      }
    },
    //打开添加页面
    addFun() {
      this.modal = true;
    },
    //打开添加页面
    updateFun(data) {
  
      this.selected = { ...data.row };
      this.updateModal = true;
    },
    //add组件callback方法
    change() {
      this.getEtlIncrementTaskList(this.currentPage);
      //刷新列表
      this.modal = false;
    },
    //update组件callback方法
    updateChange() {
      this.getEtlIncrementTaskList(this.currentPage);
      //刷新列表
      this.updateModal = false;
    },
    //执行任务
    execute(data) {
      this.executeTaskData = data.row;
      // if (data.row.flag === 0) {
      //   this.$Message.warning("任务状态禁用，无法执行！");
      //   return;
      // }
      this.$Modal.confirm({
        title: "确认执行",
        content: "您确认要执行任务吗？",
        onOk: async () => {
          if (!this.$sockets.websock.socket || this.$sockets.websock.socket.readyState === 3) {

            this.$Message.loading({
              content: "socket连接断开，尝试重连中...",
              duration: 0
            });
             this.$sockets.initWebSocket();
             let _this = this;
             let timers = setInterval(function(){
               if(_this.$sockets.websock.socket && _this.$sockets.websock.socket.readyState !== 3){

                 _this.$Message.destroy();

                 clearInterval(timers);

                 _this.$Message.success({
                    content: "socket重连成功，请重新执行任务",
                    duration: 4
                  });
               }
             },1000)

          }else{
              this.socketModal = true; //打开socket页面
          }


        }

      });
    },
    //查看历史日志
    history(data) {
      this.historyModal = true;
      this.logKid = data.row.kid;
    },
    //关闭socket连接
    socketClose(e) {
      if (!e) {
        this.getEtlIncrementTaskList(this.currentPage);
      }
    },
    //查询批次列表
    async getBatchList() {
      const data = {
        pages: 1,
        sizes: 9999
      };
      const result = await this.$api.getEtlBatchList(data);
      if (result.code === 1) {
        this.selectArr = result.data.list;
      }
    },
    //切换
    swichBatch(e) {
      this.getEtlIncrementTaskList(this.currentPage);
    },
    deleteTask(data) {
      const id = data.row.kid;
      this.$Modal.confirm({
        title: "确认删除吗？",
        okText: "确认",
        cancelText: "取消",
        loading: true,
        render: h => {
          return h("div", [
            h("p", "请输入要执行的操作类型"),
            h("span", "输入"),
            h(
              "span",
              {
                style: {
                  color: "red",
                  fontWeight: 600,
                  userSelect: "none"
                }
              },
              "‘全部删除’"
            ),
            h("span", "或"),
            h(
              "span",
              {
                style: {
                  color: "red",
                  fontWeight: 600,
                  userSelect: "none"
                }
              },
              "‘只删除表’"
            ),
            h("p", "删除后将无法恢复，请三思而行！"),
            h("Input", {
              on: {
                "on-change": event => {
                  this.deleteContent = event.target.value;
                }
              }
            })
          ]);
        },
        onOk: async () => {
          const params = {
            kid: id
          };
          if (this.deleteContent === "全部删除") {
            params.type = 1; //删除表标志
          } else if (this.deleteContent === "只删除表") {
    
          } else {
            return this.$Message.warning("输入错误，操作无效！");
          }

          const res = await this.$api.removeEtlIncrementTaskAndTable(params);
          if (res.code === 1) {
            this.$Message.info("删除表结构成功");
          } else {
            this.$Message.error(res.errMsg);
          }
          await this.getEtlIncrementTaskList(this.currentPage);

          this.deleteContent = "";
          this.$Modal.remove();
        }
      });
    }
  },
  mounted() {
    this.getEtlIncrementTaskList(this.currentPage);
    this.getBatchList();
  }
};
</script>
